package com.kevin.learn.http;

import com.alibaba.fastjson.JSON;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

public class HttpTest {
    public static void main(String[] args) throws Exception {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImUxYjY3NGE3ZTgyNmM3YTQyNWIwNDQwMDAzNDQ1N2MyZTVmYmY2M2QyYjVjZWRiMGU3ZWZjMmU2N2ZlNGFhNDQ4OTE4MGQ5MWMyZGE5NjMwIn0.eyJhdWQiOiIyMzk2MSIsImp0aSI6ImUxYjY3NGE3ZTgyNmM3YTQyNWIwNDQwMDAzNDQ1N2MyZTVmYmY2M2QyYjVjZWRiMGU3ZWZjMmU2N2ZlNGFhNDQ4OTE4MGQ5MWMyZGE5NjMwIiwiaWF0IjoxNjE0NTg2ODMyLCJuYmYiOjE2MTQ1ODY4MzIsImV4cCI6MTYxNDU5NDAzMiwic3ViIjoiIiwic2NvcGVzIjpbXX0.WbwI9KrT8Q9cAQyb2ELlbNFTNsdW4Hfd5oAmJWZAzKPIQC1eCr1kHlgmftsk4tCLzqw4flycllyG0ZbrkNOAmvaycipSAruJQlt7ZviUaWIN0lpltL1NVI1sZ33z8pADS-ew4-6ivN8Mh9heLjHpL1LXkoyCf_QYH6LVjxf7HOVtcNs6GcNZAdUKeTdQ6Eo_15AcV91KAUQdrXa8E5_maQJyglXRAUoJNFalbnLtM9GGu_4qYWS4BYVRmR0dMxonlyKpVTLDMmsRqIjoJu9CfXKGY_uYNGzFLY8df51xkn9PQl_UZOnwTVNveURSEM6eXSALR7cEC26QJYSn8HrN5Ku2ee6Ko95jWcqXHyw1G9N6hVqoSpzuJCgqlgca-1aUVorDL7A19uQLwg_oFW4enaKpKswwkw5wKYNuds55yaKtudu2dFFC3kIy0r5mO5j_hwZmZLMPIfAeJFz_fADQZXZhyc-8fqGtw_Pr5J5UQd9JQ2du_J53V-BK8JDVoH2e-FZoh5Grj8vAocCzKiKAIUQpo85cwzDAZyTjq1zkFFLWWD5fKEJ7QyVqzvW6J4vFWI7EMxal4WIXgPO8qfhWQz2nOLL10Nd2Lm3v6PRVLhxL_0S7n1GUxGFdXnKgoowwT2MkuZRm4J_8Xn-_jSpwkjl53QPzDEdzAfpHDJh_I2g";


        Map<String, String> map = new HashMap<>();
        map.put("id", "7");
//        String s = "{\n" + "    \"id\":7\n" + "}";
//        String body = HttpUtil.createRequest(Method.GET, "https://lxapi.lexiangla.com/cgi-bin/v1/contact/tag/users?access_token=" + token).body(s.getBytes("UTF-8")).execute().body();
//        System.out.println(body);


        String s = sendJsonByGetReq("https://lxapi.lexiangla.com/cgi-bin/v1/contact/tag/users?access_token=" + token, JSON.toJSONString(map));
        System.out.println(s);
    }


    public static String sendJsonByGetReq(String url, String param) throws Exception {

        String body = "";

        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
        HttpEntity httpEntity = new StringEntity(param, ContentType.APPLICATION_JSON);
        httpGetWithEntity.setEntity(httpEntity);

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpGetWithEntity);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, "utf-8");
        }
        //释放链接
        response.close();
        return body;
    }

}
